import axios  from "axios";
import {getAdminToken,getUserToken,removeAdminToken,removeUserToken} from "@/store/session.js";

const service = axios.create({
    baseURL: '/v1',
    timeout: 180000,
    withCredentials: true // // 用途：withCredentials: true 是跨域认证场景下的必要配置，用于携带 Cookies 等凭证。
})

// 请求拦截器
service.interceptors.request.use(config => {
    config.headers['Authorization'] = getUserToken()
    config.headers['Admin-Authorization'] = getAdminToken()
    return config
},err => {
    return Promise.reject(err)
})

// 响应拦截器
service.interceptors.response.use(response => {
    return response
},async err => {
    if (err.response.status === 401) {
        if (err.response.request.responseURL.indexOf('/api/admin') !== -1) {
            removeAdminToken()
        }else{
            removeUserToken()
        }
        err.response.data.message = '请先登录'
        return Promise.reject(err.response.data)
    }
    if (err.response.status === 400) {
        if(err.response.data instanceof Blob && err.response.data.type === 'application/json') {
            try {
                // 将Blob转换为文本
                const text = await err.response.data.text();
                // 替换error.response.data为解析后的数据
                err.response.data = JSON.parse(text);
            } catch (e) {
                // 如果转换失败，保持原来的错误数据
                console.error('Blob转换JSON失败', e);
            }
        }
        return Promise.reject(new Error(err.response.data.message))
    }else{
        return Promise.reject(err)
    }
})

// http get 请求
export function httpGet(url,params = {}) {
    return new Promise((resolve,reject) => {
        service.get(url,{
            params: params
        }).then(response => {
            resolve(response.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// http post 请求
export function httpPost(url,data = {},options = {}) {
    return new Promise((resolve,reject) => {
        service.post(url,data, options).then(response => {
            resolve(response.data)
        }).catch(err => {
            reject(err)
        })
    })
}

export function httpDownload(url) {
    return new Promise((resolve,reject) => {
        service({
            method: 'GET',
            url: url,
            responseType: 'blob' // 将响应类型设置为 `blob`
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

export function httpPostDownload(url,data) {
    return new Promise((resolve,reject) => {
        service({
            method: 'POST',
            url: url,
            data: data,
            responseType: 'blob' // 将响应类型设置为 `blob`
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}